package com.majie.qiniu;

import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;


/**
 * 七牛云配置
 * @author majie
 */
@Configuration
@ConditionalOnClass(UploadManager.class)
@EnableConfigurationProperties(QiNiuProperties.class)
public class QiNiuYunAutoConfiguration {

	/**
	 * 构建机房
	 */
	@Bean
	@ConditionalOnMissingBean
	public com.qiniu.storage.Configuration qiniuConfig(QiNiuProperties qiNiuProperties) {
		// 判断机房
		// 0 华东机房 1 华北 2 华南 3 北美 4新加坡 其他自动配置
		int zoneId = qiNiuProperties.getZoneId();

		com.qiniu.storage.Configuration configuration;
		switch (zoneId) {
		case 0:
			configuration = new com.qiniu.storage.Configuration(Zone.zone0());
			break;
		case 1:
			configuration = new com.qiniu.storage.Configuration(Zone.zone1());
			break;
		case 2:
			configuration = new com.qiniu.storage.Configuration(Zone.zone2());
			break;
		case 3:
			configuration = new com.qiniu.storage.Configuration(Zone.zoneNa0());
			break;
		case 4:
			configuration = new com.qiniu.storage.Configuration(Zone.zoneAs0());
			break;
		default:
            // 否则自动配置
            configuration = new com.qiniu.storage.Configuration(Zone.autoZone());
            break;
        }
		return configuration;
	}

	/**
	 * 认证信息实例
	 * 
	 */
	@Bean
	@ConditionalOnMissingBean
	public Auth auth(QiNiuProperties qiNiuProperties) {
		return Auth.create(qiNiuProperties.getAccessKey(), qiNiuProperties.getSecretKey());
	}

	/**
	 * 构建七牛空间管理实例
	 */
	@Bean
	@ConditionalOnMissingBean
	public BucketManager bucketManager(QiNiuProperties qiNiuProperties) {
		return new BucketManager(auth(qiNiuProperties), qiniuConfig(qiNiuProperties));
	}

	/**
	 * 构建一个七牛上传工具实例
	 */
	@Bean
	@ConditionalOnMissingBean
	public UploadManager uploadManager(QiNiuProperties qiNiuProperties) {
		return new UploadManager(qiniuConfig(qiNiuProperties));
	}

	/**
	 * 构建一个七牛云工具类
	 * 
	 * @return
	 */
	@Bean
	@ConditionalOnMissingBean
	public QiNiuYunService qiNiuYunService() {
		return new QiNiuYunService();
	}
}
